#include "product_edit_dialog.h"
#include "ui_product_edit_dialog.h"
#include "database_manager.h"
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>

ProductEditDialog::ProductEditDialog(QWidget *parent, int productId) :
    QDialog(parent),
    ui(new Ui::ProductEditDialog),
    currentProductId(productId) {
    
    ui->setupUi(this);
    setWindowTitle(productId == -1 ? "添加产品" : "编辑产品");
    
    connect(ui->saveButton, &QPushButton::clicked, this, &ProductEditDialog::onSaveButtonClicked);
    connect(ui->cancelButton, &QPushButton::clicked, this, &ProductEditDialog::onCancelButtonClicked);
    
    if (productId != -1) {
        loadProductData();
    }
}

ProductEditDialog::~ProductEditDialog() {
    delete ui;
}

void ProductEditDialog::loadProductData() {
    QSqlQuery query;
    query.prepare("SELECT name, barcode, price, cost, stock_quantity, "
                 "min_stock, category, supplier, description "
                 "FROM products WHERE id = ?");
    query.addBindValue(currentProductId);
    
    if (query.exec() && query.next()) {
        ui->nameEdit->setText(query.value(0).toString());
        ui->barcodeEdit->setText(query.value(1).toString());
        ui->priceSpinBox->setValue(query.value(2).toDouble());
        ui->costSpinBox->setValue(query.value(3).toDouble());
        ui->stockSpinBox->setValue(query.value(4).toInt());
        ui->minStockSpinBox->setValue(query.value(5).toInt());
        ui->categoryEdit->setText(query.value(6).toString());
        ui->supplierEdit->setText(query.value(7).toString());
        ui->descriptionEdit->setPlainText(query.value(8).toString());
    }
}

Product ProductEditDialog::getProductData() const {
    Product product;
    product.id = currentProductId;
    product.name = ui->nameEdit->text().trimmed();
    product.barcode = ui->barcodeEdit->text().trimmed();
    product.price = ui->priceSpinBox->value();
    product.cost = ui->costSpinBox->value();
    product.stockQuantity = ui->stockSpinBox->value();
    product.minStock = ui->minStockSpinBox->value();
    product.category = ui->categoryEdit->text().trimmed();
    product.supplier = ui->supplierEdit->text().trimmed();
    product.description = ui->descriptionEdit->toPlainText().trimmed();
    return product;
}

void ProductEditDialog::onSaveButtonClicked() {
    if (ui->nameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入产品名称");
        ui->nameEdit->setFocus();
        return;
    }
    
    if (ui->barcodeEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入条形码");
        ui->barcodeEdit->setFocus();
        return;
    }
    
    if (ui->priceSpinBox->value() <= 0) {
        QMessageBox::warning(this, "警告", "售价必须大于0");
        ui->priceSpinBox->setFocus();
        return;
    }
    
    accept();
}

void ProductEditDialog::onCancelButtonClicked() {
    reject();
}